'use client'

import { useState, useEffect } from 'react'
import { PlusIcon, EyeIcon, DocumentTextIcon, InformationCircleIcon, PlayIcon } from '@heroicons/react/24/outline'
import Link from 'next/link'

interface Video {
  id: number
  videoId: string
  url: string
  title: string | null
  description: string | null
  author: string | null
  likes: number | null
  shares: number | null
  comments: number | null
  views: number | null
  createdAt: string
}

export default function VideosPage() {
  const [videos, setVideos] = useState<Video[]>([])
  const [loading, setLoading] = useState(true)
  const [showAddForm, setShowAddForm] = useState(false)
  const [newVideoUrl, setNewVideoUrl] = useState('')
  const [collecting, setCollecting] = useState(false)

  useEffect(() => {
    fetchVideos()
  }, [])

  const fetchVideos = async () => {
    try {
      const response = await fetch('/api/tiktok/videos')
      if (response.ok) {
        const data = await response.json()
        setVideos(data.videos)
      }
    } catch (error) {
      console.error('Failed to fetch videos:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleCollectVideo = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newVideoUrl.trim()) return

    setCollecting(true)
    try {
      const response = await fetch('/api/tiktok/collect', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ videoUrl: newVideoUrl }),
      })

      if (response.ok) {
        setNewVideoUrl('')
        setShowAddForm(false)
        fetchVideos() // 刷新列表
      } else {
        const data = await response.json()
        alert(data.error || '采集失败')
      }
    } catch (error) {
      alert('网络错误，请重试')
    } finally {
      setCollecting(false)
    }
  }

  const handleExtractText = async (videoId: number) => {
    try {
      const response = await fetch('/api/tiktok/extract-text', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ videoId }),
      })

      if (response.ok) {
        alert('文案提取已开始，请稍后查看结果')
      } else {
        const data = await response.json()
        alert(data.error || '提取失败')
      }
    } catch (error) {
      alert('网络错误，请重试')
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  return (
    <div>
      <div className="sm:flex sm:items-center">
        <div className="sm:flex-auto">
          <h1 className="text-xl font-semibold text-gray-900">视频管理</h1>
          <p className="mt-2 text-sm text-gray-700">
            管理已采集的TikTok视频数据
          </p>
        </div>
        <div className="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
          <button
            type="button"
            onClick={() => setShowAddForm(true)}
            className="inline-flex items-center justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:w-auto"
          >
            <PlusIcon className="-ml-1 mr-2 h-5 w-5" />
            采集视频
          </button>
        </div>
      </div>

      {/* 添加视频表单 */}
      {showAddForm && (
        <div className="mt-6 bg-white shadow sm:rounded-lg">
          <div className="px-4 py-5 sm:p-6">
            <h3 className="text-lg leading-6 font-medium text-gray-900">
              采集TikTok视频
            </h3>
            <div className="mt-2 max-w-xl text-sm text-gray-500">
              <p>请输入TikTok视频的完整URL链接</p>
            </div>
            <form onSubmit={handleCollectVideo} className="mt-5">
              <div className="flex rounded-md shadow-sm">
                <input
                  type="url"
                  value={newVideoUrl}
                  onChange={(e) => setNewVideoUrl(e.target.value)}
                  className="flex-1 min-w-0 block w-full px-3 py-2 rounded-none rounded-l-md border-gray-300 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
                  placeholder="https://www.tiktok.com/@username/video/1234567890"
                  required
                />
                <button
                  type="submit"
                  disabled={collecting}
                  className="inline-flex items-center px-3 py-2 border border-l-0 border-gray-300 rounded-r-md bg-gray-50 text-gray-500 text-sm disabled:opacity-50"
                >
                  {collecting ? '采集中...' : '开始采集'}
                </button>
              </div>
              <div className="mt-3 flex justify-end space-x-3">
                <button
                  type="button"
                  onClick={() => setShowAddForm(false)}
                  className="bg-white py-2 px-4 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                  取消
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 视频列表 */}
      <div className="mt-8 flex flex-col">
        <div className="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8">
          <div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
            <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
              <table className="min-w-full divide-y divide-gray-300">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      视频信息
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      作者信息
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      互动数据
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      视频详情
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wide">
                      发布时间
                    </th>
                    <th className="relative px-6 py-3">
                      <span className="sr-only">操作</span>
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {videos.map((video) => {
                    // 解析话题标签
                    let hashtags = []
                    try {
                      hashtags = video.hashtags ? JSON.parse(video.hashtags) : []
                    } catch (e) {
                      hashtags = []
                    }

                    return (
                      <tr key={video.id}>
                        <td className="px-6 py-4">
                          <div className="flex items-center">
                            {/* 封面图片 */}
                            {video.coverUrl && (
                              <div className="flex-shrink-0 h-16 w-16 mr-4">
                                <img
                                  src={video.coverUrl}
                                  alt="视频封面"
                                  className="h-16 w-16 rounded-lg object-cover"
                                />
                              </div>
                            )}
                            <div className="flex-1 min-w-0">
                              <div className="text-sm font-medium text-gray-900 truncate">
                                {video.title || video.description?.substring(0, 50) + '...' || `视频 ${video.videoId}`}
                              </div>
                              <div className="text-sm text-gray-500 max-w-xs truncate">
                                {video.description}
                              </div>
                              {/* 话题标签 */}
                              {hashtags.length > 0 && (
                                <div className="mt-1 flex flex-wrap gap-1">
                                  {hashtags.slice(0, 2).map((tag: any, index: number) => (
                                    <span
                                      key={index}
                                      className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800"
                                    >
                                      #{tag.name}
                                    </span>
                                  ))}
                                  {hashtags.length > 2 && (
                                    <span className="text-xs text-gray-400">+{hashtags.length - 2}</span>
                                  )}
                                </div>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="text-sm text-gray-900">
                            <div className="font-medium">@{video.author || '-'}</div>
                            {video.authorFollowers && (
                              <div className="text-gray-500">
                                {video.authorFollowers.toLocaleString()} 粉丝
                              </div>
                            )}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          <div className="space-y-1">
                            <div className="flex items-center">
                              <span className="text-red-500">❤️</span>
                              <span className="ml-1">{video.likes?.toLocaleString() || 0}</span>
                            </div>
                            <div className="flex items-center">
                              <span className="text-blue-500">👁️</span>
                              <span className="ml-1">{video.views?.toLocaleString() || 0}</span>
                            </div>
                            <div className="flex items-center">
                              <span className="text-green-500">💬</span>
                              <span className="ml-1">{video.comments?.toLocaleString() || 0}</span>
                            </div>
                            <div className="flex items-center">
                              <span className="text-purple-500">📤</span>
                              <span className="ml-1">{video.shares?.toLocaleString() || 0}</span>
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          <div className="space-y-1">
                            {video.duration && (
                              <div>⏱️ {video.duration}秒</div>
                            )}
                            {video.musicTitle && (
                              <div className="truncate max-w-32" title={video.musicTitle}>
                                🎵 {video.musicTitle}
                              </div>
                            )}
                            <div className="text-xs text-gray-400">
                              ID: {video.videoId.substring(0, 8)}...
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                          <div>
                            {video.publishTime
                              ? new Date(video.publishTime).toLocaleDateString('zh-CN')
                              : new Date(video.createdAt).toLocaleDateString('zh-CN')
                            }
                          </div>
                          <div className="text-xs text-gray-400">
                            采集: {new Date(video.createdAt).toLocaleDateString('zh-CN')}
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                          <div className="flex space-x-2">
                            <Link
                              href={`/videos/${video.id}`}
                              className="text-gray-600 hover:text-gray-900"
                              title="查看详情"
                            >
                              <InformationCircleIcon className="h-5 w-5" />
                            </Link>
                            <a
                              href={video.url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="text-indigo-600 hover:text-indigo-900"
                              title="在TikTok上查看"
                            >
                              <EyeIcon className="h-5 w-5" />
                            </a>
                            {video.videoUrl && (
                              <a
                                href={video.videoUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-blue-600 hover:text-blue-900"
                                title="直接播放"
                              >
                                <PlayIcon className="h-5 w-5" />
                              </a>
                            )}
                            <button
                              onClick={() => handleExtractText(video.id)}
                              className="text-green-600 hover:text-green-900"
                              title="提取文案"
                            >
                              <DocumentTextIcon className="h-5 w-5" />
                            </button>
                          </div>
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
              {videos.length === 0 && (
                <div className="text-center py-12">
                  <p className="text-gray-500">暂无视频数据，点击"采集视频"开始添加</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
